# -*- coding: utf-8 -*-

'''eof
name:申请企业注册年限校验
code:R05_EG_EntRegisterCheck
tableName:
columnName:
groups:企业业务信息校验
dependencies:EG_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''


import sys
import pandas as pd
import json
from datetime import datetime


def FormatData(tableName):
    try:
        eg = EG_DSJ.get("data").get("R1103V3")[0].get(tableName)
        return eg if isinstance(eg, list) else [{}]
    except:
        return [{}]


def diff_date(str1):
    try:
        date1 = datetime.now()
        date2 = date_format(str1[0:10])
        diff_year = date1.year - date2.year
        diff_month = date1.month - date2.month
        diff_day = date1.day - date2.day
        age = diff_year + diff_month/12.0 + diff_day/365.0
        return '%.4f' % age
    except:
        return None


# 统一转成datetime对象，只能转年月日的字符串
def date_format(time):
    import re
    r = re.compile(r'\D+')
    try:
        date = datetime.strptime(time, '%Y.%m.%d')
    except:
        try:
            date = datetime.strptime(time, '%Y-%m-%d')
        except:
            try:
                date = datetime.strptime(time, '%Y/%m/%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.strptime(tmp, '%Y%m%d')
                except:
                    date = None
    return date


def getRule05():
    null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']
    basic_list = FormatData("basicList")
    if basic_list == [{}]:
        return u'缺失值'
    else:
        if len(basic_list) >= 1:
            for i in basic_list:
                es_date = i.get("esDate")
                diff_years = diff_date(es_date)
                if es_date not in null_type_list and diff_years not in null_type_list:
                    return diff_years
                else:
                    return u'缺失值'
            return u'缺失值'
        else:
            return u'缺失值'


if __name__ == "__main__":
    ratingRequest = {"card_id":"500101199201122461","bb":""}
    file_obj = open(r'../data/rating/R05_EG_EntRegisterCheck/EG_DSJ.json', 'r')
    content = file_obj.read()
    EG_DSJ = json.loads(content, strict=False)
    aa = getRule05()
    print aa

result = getRule05()

